package keywords

import (
	"context"

	"gorm.io/gorm"
)

type Keywords struct {
	ID          uint64 `db:"id" gorm:"primaryKey;autoIncrement;comment:关键词 id"`
	KUId        uint64 `db:"k_u_id" gorm:"column:k_u_id;default:0;not null"`
	KName       string `db:"k_name" gorm:"column:k_name;size:255;default:''"`
	KGrade      string `db:"k_grade" gorm:"column:k_grade;size:255;default:''"`
	KSubject    string `db:"k_subject" gorm:"column:k_subject;size:255;default:''"`
	KDifficulty string `db:"k_difficulty" gorm:"column:k_difficulty;size:255;default:''"`
	CreatedAt   int64  `db:"created_at" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt   int64  `db:"updated_at" gorm:"autoUpdateTime;comment:更新时间"`
}

// TableName sets the table name for the model
func (Keywords) TableName() string {
	return "keywords"
}

type KeywordsModelInterface interface {
	Delete(ctx context.Context, kId uint64) error
	FindOne(ctx context.Context, kId uint64) (*Keywords, error)
	Insert(ctx context.Context, data *Keywords) error
	Update(ctx context.Context, data *Keywords) error
	FindByKUId(uid uint64) ([]*Keywords, error)
}

type KeywordsModel struct {
	db *gorm.DB
}

func NewKeywordsModel(db *gorm.DB) *KeywordsModel {
	return &KeywordsModel{
		db: db,
	}
}

func (m *KeywordsModel) Delete(ctx context.Context, kId uint64) error {
	return m.db.Where("id = ?", kId).Delete(&Keywords{}).Error
}

func (m *KeywordsModel) FindOne(ctx context.Context, kId uint64) (*Keywords, error) {
	var keyword Keywords
	err := m.db.Where("id = ?", kId).First(&keyword).Error
	if err != nil {
		return nil, err
	}
	return &keyword, nil
}

func (m *KeywordsModel) Insert(ctx context.Context, data *Keywords) error {
	return m.db.Create(data).Error
}

func (m *KeywordsModel) Update(ctx context.Context, data *Keywords) error {
	return m.db.Save(data).Error
}

func (m *KeywordsModel) FindByKUId(uid uint64) ([]*Keywords, error) {
	var keywords []*Keywords
	err := m.db.Where("k_u_id = ?", uid).Find(&keywords).Error
	if err != nil {
		return nil, err
	}
	return keywords, nil
}
